const { JsonDB } = require('node-json-db')
const { Config } = require('node-json-db/dist/lib/JsonDBConfig')

const db = new JsonDB(new Config('./ppy_authapi.json'), true, true, '/')

const ppy_authapi = async (ctx) => {
    let ops = {
        error_code: 0,
        host_type: 'ssh',
        use_s5proxy: false,
        proxy: {
            host: '127.0.0.1', // ipv4 or ipv6 or hostname
            port: 1080,
            type: 5 // Proxy version (4 or 5)
        },
        command: 'connect', // SOCKS command (createConnection factory function only supports the connect command)
        destination: {
            host: '', // github.com (hostname lookups are supported with SOCKS v4a and 5)
            port: 22
        },
        account:{
            username: 'root',
            password: ''
        }
    };
    
    db.reload()    
    const asset_id = ctx.request.query.asset_id;
    if(asset_id == null) return;
    console.log("get asset_id:" + asset_id)
    const res = await db.filter('/assets', function(value, index) {
        if (value.id == asset_id) {
            return true
        }
        return false
    });
    
    if(res.length == 0){
        ops.error_code = 1;
        console.log(ops);
        ctx.body = JSON.stringify(ops);
        return;
    }
 
    const hostinfo = res[0];   
    console.log("find host by asset_id:" + hostinfo.id);
    
    ops.host_type = hostinfo.type;
    if(ops.host_type == 'ssh'){
        ops.destination.host = hostinfo.host;
        ops.destination.port = hostinfo.port;
        ops.account.username = hostinfo.username;
        ops.account.password = hostinfo.password;
        ops.use_s5proxy = hostinfo.use_s5proxy;
    
        if(ops.use_s5proxy == true){
            console.log(hostinfo.s5proxy);
            const res1 = await db.getData('/s5proxy/' + hostinfo.s5proxy);
            console.log("s5proxy:" + res1.host);
            console.log("s5proxy:" + res1.port);
            ops.proxy.host = res1.host;
            ops.proxy.port = res1.port;
        }
    }else{
        ops.error_code = 2;
    }

    console.log(ops);
    ctx.body = JSON.stringify(ops);
}

module.exports = {
    ppy_authapi
}